package team.seekers.hula.system.resource.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import team.seekers.hula.common.entity.PageResult;
import team.seekers.hula.system.resource.dao.VideoDao;
import team.seekers.hula.system.resource.entity.VideoDO;
import team.seekers.hula.system.resource.entity.dto.*;

import java.util.ArrayList;

/**
 * date: 2022/4/25 21:45
 *
 * @author hbc
 * QQ 1753912621
 */
@Slf4j
@Service
public class VideoService {

    @Autowired
    private VideoDao videoDao;

    @Autowired
    private DemandService demandService;

    public PageResult<VideoListDTO> query(String nameKey) {

        LambdaQueryChainWrapper<VideoDO> query = videoDao.lambdaQuery().select(
                VideoDO::getId,
                VideoDO::getName,
                VideoDO::getExtensionName,
                VideoDO::getOss
        );
        if (StringUtils.isNotBlank(nameKey)) {
            query.like(VideoDO::getName, nameKey);
        }
        Page<VideoDO> page = query.page(new Page<>(1, 20));

        ArrayList<VideoListDTO> videoListDTOS = new ArrayList<>();
        for (VideoDO record : page.getRecords()) {
            VideoListDTO videoListDTO = new VideoListDTO();
            BeanUtils.copyProperties(record, videoListDTO);
            videoListDTOS.add(videoListDTO);
        }
        return new PageResult<>(page.getPages(), videoListDTOS);
    }

    public String save(VideoCreateDTO videoCreateDTO) {
        VideoDO VideoDO = new VideoDO();
        BeanUtils.copyProperties(videoCreateDTO,VideoDO);
        videoDao.save(VideoDO);
        return VideoDO.getId();
    }

    public VideoDTO queryInfoById(@RequestParam String videoId) {
        VideoDO VideoDO = videoDao.getById(videoId);
        VideoDTO videoDTO = new VideoDTO();
        BeanUtils.copyProperties(VideoDO, videoDTO);

        // 视频
        videoDTO.setAuth(demandService.getVideoPlayAuth(VideoDO.getOss()).getPlayAuth());
        videoDTO.setPlayUrl(demandService.getVideoPlayUrl(VideoDO.getOss()));
        videoDTO.setDuration(VideoDO.getSize());


        return videoDTO;
    }

    public SectionContentBindDTOS saveBindDTO(SectionContentBindDTOS sectionContentBindDTOS) {
        for (SectionContentBindDTO sectionContent : sectionContentBindDTOS.getSectionContentBindDTOS()) {
            VideoDO VideoDO = new VideoDO();
            BeanUtils.copyProperties(sectionContent,VideoDO);
            videoDao.save(VideoDO);
            sectionContent.setResourceId(VideoDO.getId());
        }
        return sectionContentBindDTOS;
    }
}
